package com.yckj.activechicken.business.purchase.service.impl;

import com.yckj.activechicken.business.common.mapper.ApproverInfoMapper;
import com.yckj.activechicken.business.common.mapper.CustomSequenceMapper;
import com.yckj.activechicken.business.common.service.IProcessService;
import com.yckj.activechicken.business.purchase.mapper.*;
import com.yckj.activechicken.business.purchase.mapper.comp.PurApplyBillMapperComp;
import com.yckj.activechicken.business.purchase.model.*;
import com.yckj.activechicken.business.purchase.model.vo.PurApplyBillVo;
import com.yckj.activechicken.business.purchase.model.vo.PurApplyGoodsBillVo;
import com.yckj.activechicken.business.purchase.model.vo.PurApplyTaskVo;
import com.yckj.activechicken.business.purchase.service.IPurApplyService;
import com.yckj.activechicken.business.system.service.ISysUserService;
import com.yckj.activechicken.common.constant.ProcessContants;
import com.yckj.activechicken.common.utils.StringUtils;
import com.yckj.activechicken.common.utils.security.SecurityUtils;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * <p>
 * Title:com.yckj.activechicken.business.purchase.service.impl
 * </p>
 * <p/>
 * <p>
 * Description: 描述【采购申请业务处理实体】
 * </p>
 * <p/>
 * <p>
 * Copyright: Copyright (c) 2019
 * </p>
 * <p/>
 * <p>
 * Company: 英才汇硕信息技术有限公司
 * </p>
 *
 * @author zhoujy
 * @version 1.0
 * @created 2020/6/13 10:26
 */
@Service
public class PurApplyServiceImpl implements IPurApplyService {
    @Autowired
    private CustomSequenceMapper customSequenceMapper;

    @Autowired
    private PurApplyBillMapper purApplyBillMapper;

    @Autowired
    private PurApplyGoodsBillMapper purApplyGoodsBillMapper;

    @Autowired
    private PurGoodsMovingMapper purGoodsMovingMapper;

    @Autowired
    private PurApplyBillMapperComp purApplyBillMapperComp;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private PurMainBillMapper purMainBillMapper;

    @Autowired
    private PurNodeBillMapper purNodeBillMapper;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private ApproverInfoMapper approverInfoMapper;

    @Autowired
    private IProcessService processService;

    /**
     * 保存采购申请单
     * @param purApplyBillVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String addApplyBill(PurApplyBillVo purApplyBillVo) {
        //获取主键值
        String purApplyId = customSequenceMapper.selectNextVal("pur_apply_id");
        String username = SecurityUtils.getUsername();
        Date newDate = new Date();

        //添加申请单主表
        PurApplyBill purApplyBill = new PurApplyBill();
        BeanUtils.copyProperties(purApplyBillVo,purApplyBill);
        purApplyBill.setPurApplyId(purApplyId);
        purApplyBill.setApprovalStatus("未提交");
        purApplyBill.setCreateBy(username);
        purApplyBill.setCreateTime(newDate);
        purApplyBill.setUpdateBy(username);
        purApplyBill.setUpdateTime(newDate);
        purApplyBillMapper.insertSelective(purApplyBill);


        List<PurApplyGoodsBillVo> purApplyGoodsBillVoList = purApplyBillVo.getPurApplyGoodsBillVoList();
        if(StringUtils.isNotEmpty(purApplyGoodsBillVoList)){
            for(PurApplyGoodsBillVo purApplyGoodsBillVo : purApplyGoodsBillVoList){
                //添加申请货品清单
                PurApplyGoodsBill purApplyGoodsBill = new PurApplyGoodsBill();
                BeanUtils.copyProperties(purApplyGoodsBillVo,purApplyGoodsBill);
                String purApplyGoodsId = customSequenceMapper.selectNextVal("pur_apply_goods_id");
                purApplyGoodsBill.setPurApplyGoodsId(purApplyGoodsId);
                purApplyGoodsBill.setPurApplyId(purApplyId);
                purApplyGoodsBill.setCreateBy(username);
                purApplyGoodsBill.setCreateTime(newDate);
                purApplyGoodsBill.setUpdateBy(username);
                purApplyGoodsBill.setUpdateTime(newDate);
                purApplyGoodsBillMapper.insertSelective(purApplyGoodsBill);

                //添加货品流转信息表
                PurGoodsMoving purGoodsMoving = new PurGoodsMoving();
                purGoodsMoving.setGoodsId(purApplyGoodsBillVo.getGoodsId());
                purGoodsMoving.setGoodsName(purApplyGoodsBillVo.getGoodsName());
                purGoodsMoving.setGoodsNumber(purApplyGoodsBillVo.getGoodsNumber());
                purGoodsMoving.setGoodsMeasurementUnit(purApplyGoodsBillVo.getGoodsMeasurementUnit());
                purGoodsMoving.setPurApplyId(purApplyId);
                purGoodsMovingMapper.insertSelective(purGoodsMoving);
            }
        }

        return purApplyId;
    }

    /**
     * 多条件查询采购申请单信息
     * @param purApplyBill
     * @return
     */
    @Override
    public List<PurApplyBill> listApplyBill(PurApplyBill purApplyBill) {
        return purApplyBillMapperComp.selectPurApplyBillList(purApplyBill);
    }

    /**
     * 通过申请单号删除申请单
     * @param purApplyBill
     * @return
     */
    @Override
    public int delApplyBill(PurApplyBill purApplyBill) {
        return purApplyBillMapper.updateByPrimaryKeySelective(purApplyBill);
    }

    /**
     * 修改采购申请单
     * @param purApplyBillVo
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void modifyApplyBill(PurApplyBillVo purApplyBillVo) {
        Date newDate = new Date();
        String username = SecurityUtils.getUsername();
        String purApplyId = purApplyBillVo.getPurApplyId();

        //修改主申请单
        PurApplyBill purApplyBill = new PurApplyBill();
        BeanUtils.copyProperties(purApplyBillVo,purApplyBill);
        purApplyBill.setUpdateTime(newDate);
        purApplyBillMapper.updateByPrimaryKeySelective(purApplyBill);

        //修改采购清单
        List<PurApplyGoodsBillVo> purApplyGoodsBillVoList = purApplyBillVo.getPurApplyGoodsBillVoList();
        if(StringUtils.isNotEmpty(purApplyGoodsBillVoList)){
            for(PurApplyGoodsBillVo purApplyGoodsBillVo : purApplyGoodsBillVoList){
                PurApplyGoodsBill purApplyGoodsBill = new PurApplyGoodsBill();
                BeanUtils.copyProperties(purApplyGoodsBillVo,purApplyGoodsBill);
                //修改
                if(purApplyGoodsBill.getPurApplyGoodsId() != null){
                    purApplyGoodsBill.setUpdateTime(newDate);
                    purApplyGoodsBillMapper.updateByPrimaryKeySelective(purApplyGoodsBill);
                }else{
                    //添加
                    String purApplyGoodsId = customSequenceMapper.selectNextVal("pur_apply_goods_id");
                    purApplyGoodsBill.setPurApplyGoodsId(purApplyGoodsId);
                    purApplyGoodsBill.setPurApplyId(purApplyId);
                    purApplyGoodsBill.setCreateBy(username);
                    purApplyGoodsBill.setCreateTime(newDate);
                    purApplyGoodsBill.setUpdateBy(username);
                    purApplyGoodsBill.setUpdateTime(newDate);
                    purApplyGoodsBillMapper.insertSelective(purApplyGoodsBill);
                }
            }
        }

        //删除部分采购货品记录
        List<PurApplyGoodsBillVo> deleteGoodsList = purApplyBillVo.getDeleteGoodsList();
        if(StringUtils.isNotEmpty(deleteGoodsList)){
            for(PurApplyGoodsBillVo purApplyGoodsBillVo : deleteGoodsList){
                purApplyGoodsBillMapper.deleteByPrimaryKey(purApplyGoodsBillVo.getPurApplyGoodsId());
            }
        }

        //处理货品流转记录表
        //删除原有记录
        PurGoodsMovingExample purGoodsMovingExample = new PurGoodsMovingExample();
        purGoodsMovingExample.createCriteria().andPurApplyIdEqualTo(purApplyId);
        purGoodsMovingMapper.deleteByExample(purGoodsMovingExample);
        //添加新纪录
        if(StringUtils.isNotEmpty(purApplyGoodsBillVoList)){
            for(PurApplyGoodsBillVo purApplyGoodsBillVo : purApplyGoodsBillVoList){
                PurGoodsMoving purGoodsMoving = new PurGoodsMoving();
                purGoodsMoving.setGoodsId(purApplyGoodsBillVo.getGoodsId());
                purGoodsMoving.setGoodsName(purApplyGoodsBillVo.getGoodsName());
                purGoodsMoving.setGoodsNumber(purApplyGoodsBillVo.getGoodsNumber());
                purGoodsMoving.setGoodsMeasurementUnit(purApplyGoodsBillVo.getGoodsMeasurementUnit());
                purGoodsMoving.setPurApplyId(purApplyId);
                purGoodsMovingMapper.insertSelective(purGoodsMoving);
            }
        }

    }

    /**
     * 查询申请单的用户信息以及货品清单
     * @param purApplyBill
     * @return
     */
    @Override
    public Map<String, Object> queryGoodsBillAndUserInfo(PurApplyBill purApplyBill) {
        Map<String,Object> outMap = new HashMap<>(3);

        String applyUser = purApplyBill.getApplyUser();
        String roleNames = sysUserService.selectUserRoleGroup(applyUser);
        String postNames = sysUserService.selectUserPostGroup(applyUser);

        outMap.put("roleNames",roleNames);
        outMap.put("postNames",postNames);

        List<PurApplyGoodsBillVo> purApplyGoodsBillList = purApplyBillMapperComp.selectGoodsBillList(purApplyBill);


        outMap.put("purApplyGoodsBillList",purApplyGoodsBillList);

        return outMap;
    }

    /**
     * 发起采购申请单审批
     * @param purApplyBill
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> submitApproval(PurApplyBill purApplyBill) {
        Map<String,Object> outMap = new HashMap<>(2);
        String purMainId = customSequenceMapper.selectNextVal("pur_main_id");
        String username = SecurityUtils.getUsername();
        Date newDate = new Date();

        /*
         * 1、校验发起人是否为当前用户
         */
        if(!StringUtils.equals(username,purApplyBill.getApplyUser())){
            outMap.put("result","false");
            outMap.put("message","只有采购申请者能够发起申请审批，请确认身份！");
            return outMap;
        }

        /*
         * 2、采购主流程记录添加
         */
        PurMainBill purMainBill = new PurMainBill();
        purMainBill.setPurMainId(purMainId);
        purMainBill.setPurPlanName(purApplyBill.getApplyTitle());
        purMainBill.setBeginUser(purApplyBill.getApplyUser());
        purMainBill.setBeginUserName(purApplyBill.getApplyUserName());
        purMainBill.setBeginTime(newDate);
        purMainBill.setExecuteNode("采购申请审批发起");
        purMainBill.setExecuteStatus("审批中");
        purMainBill.setCreateBy(username);
        purMainBill.setCreateTime(newDate);
        purMainBill.setUpdateBy(username);
        purMainBill.setUpdateTime(newDate);
        purMainBillMapper.insertSelective(purMainBill);

        /*
         * 3、采购环节记录添加
         */
        PurNodeBill purNodeBill = new PurNodeBill();
        purNodeBill.setPurMainId(purMainId);
        purNodeBill.setExecuteNode("采购申请审批发起");
        purNodeBill.setExecuteStatus("审批中");
        purNodeBill.setBusinessId(purApplyBill.getPurApplyId());
        purNodeBill.setCreateBy(username);
        purNodeBill.setCreateTime(newDate);
        purNodeBillMapper.insertSelective(purNodeBill);

        /*
         * 4、启动审批流程
         */
        Map<String,String> queryMap = new HashMap<>(5);
        queryMap.put("processDefinitionKey",ProcessContants.PROCESS_PURAPPLYPROCESS);
        queryMap.put("businessId",purApplyBill.getPurApplyId());
        queryMap.put("applyUser",purApplyBill.getApplyUser());

        Map<String,String> outProcessMap = processService.doStartProcess(queryMap);
        String processInstanceId = outProcessMap.get("processInstanceId");
        String approvalUser = outProcessMap.get("approvalUser");
        String taskName = outProcessMap.get("taskName");


        /*
         * 5、更新申请单审批状态
         */
        purApplyBill.setPurMainId(purMainId);
        purApplyBill.setApplyTime(newDate);
        purApplyBill.setApprovalNode(taskName);
        purApplyBill.setApprovalUser(approvalUser);
        purApplyBill.setApprovalStatus("审批中");
        purApplyBill.setApprovalInstanceId(processInstanceId);
        purApplyBill.setUpdateBy(username);
        purApplyBill.setUpdateTime(newDate);
        purApplyBillMapper.updateByPrimaryKeySelective(purApplyBill);

        /*
         * 6、更新申请货品清单表
         */
        PurApplyGoodsBillExample goodsBillExample = new PurApplyGoodsBillExample();
        goodsBillExample.createCriteria().andPurApplyIdEqualTo(purApplyBill.getPurApplyId());
        PurApplyGoodsBill purApplyGoodsBill = new PurApplyGoodsBill();
        purApplyGoodsBill.setPurMainId(purMainId);
        purApplyGoodsBill.setUpdateBy(username);
        purApplyGoodsBill.setUpdateTime(newDate);
        purApplyGoodsBillMapper.updateByExampleSelective(purApplyGoodsBill,goodsBillExample);

        /*
         * 7、更新货品流转表
         */
        PurGoodsMovingExample purGoodsMovingExample = new PurGoodsMovingExample();
        purGoodsMovingExample.createCriteria().andPurApplyIdEqualTo(purApplyBill.getPurApplyId());
        PurGoodsMoving purGoodsMoving = new PurGoodsMoving();
        purGoodsMoving.setPurMainId(purMainId);
        purGoodsMovingMapper.updateByExampleSelective(purGoodsMoving,purGoodsMovingExample);

        outMap.put("result","true");

        return outMap;
    }

    /**
     * 查询申请单待办列表
     * @param purApplyBill
     * @return
     */
    @Override
    public List<PurApplyTaskVo> queryTodoPurApplyList(PurApplyBill purApplyBill) {
        List<PurApplyTaskVo> taskVoList = new ArrayList<>();
        //获取当前操作者用户名
        String username = SecurityUtils.getUsername();

        //查询候选人待办任务列表
        List<Task> taskList = taskService.createTaskQuery().taskCandidateUser(username).list();

        if(StringUtils.isNotEmpty(taskList)){
            for(Task task : taskList){
                //获取当前任务的业务处理id，businessKey
                String processInstanceId = task.getProcessInstanceId();
                ProcessInstance processInstance = runtimeService.createProcessInstanceQuery()
                        .processInstanceId(processInstanceId).singleResult();
                String businessKey = processInstance.getBusinessKey();

                //根据业务id获取采购申请单
                PurApplyBill queryPurApplyBill = purApplyBillMapper.selectByPrimaryKey(businessKey);
                PurApplyTaskVo purApplyTaskVo = new PurApplyTaskVo();
                if(queryPurApplyBill != null){
                    //过滤请求条件
                    if (StringUtils.isNotBlank(purApplyBill.getPurApplyId()) && !queryPurApplyBill.getPurApplyId().equals(purApplyBill.getPurApplyId())) {
                        continue;
                    }
                    if (StringUtils.isNotBlank(purApplyBill.getApplyTitle()) && !queryPurApplyBill.getApplyTitle().contains(purApplyBill.getApplyTitle())) {
                        continue;
                    }
                    if (StringUtils.isNotBlank(purApplyBill.getApplyUser()) && !queryPurApplyBill.getApplyUser().contains(purApplyBill.getApplyUser())) {
                        continue;
                    }
                    if (StringUtils.isNotBlank(purApplyBill.getApplyUserName()) && !queryPurApplyBill.getApplyUserName().contains(purApplyBill.getApplyUserName())) {
                        continue;
                    }
                    if (StringUtils.isNotBlank(purApplyBill.getDeptName()) && !queryPurApplyBill.getDeptName().contains(purApplyBill.getDeptName())) {
                        continue;
                    }

                    //组装信息到输出对象
                    BeanUtils.copyProperties(queryPurApplyBill,purApplyTaskVo);
                    purApplyTaskVo.setProcessInstanceId(processInstanceId);
                    purApplyTaskVo.setTaskId(task.getId());
                    purApplyTaskVo.setTaskName(task.getName());
                }

                taskVoList.add(purApplyTaskVo);
            }
        }


        return taskVoList;
    }

    /**
     * 采购申请单审批
     * @param purApplyTaskVo
     * @return
     */
    @Override
    public void approvalApply(PurApplyTaskVo purApplyTaskVo) {
        String username = SecurityUtils.getUsername();
        String name = SecurityUtils.getLoginUser().getUser().getLoginName();
        Date newDate = new Date();

        Map<String,String> queryMap = new HashMap<>();
        queryMap.put("applyUser",purApplyTaskVo.getApplyUser());
        queryMap.put("taskId",purApplyTaskVo.getTaskId());
        queryMap.put("processInstanceId",purApplyTaskVo.getProcessInstanceId());
        queryMap.put("approval",purApplyTaskVo.getApproval());
        queryMap.put("approvalComment",purApplyTaskVo.getApprovalComment());

        Map<String,String> outMap = processService.doTaskAndStartNextTask(queryMap);
        String approvalUser = outMap.get("approvalUser");
        String taskName = outMap.get("taskName");
        String approvalStatus = outMap.get("approvalStatus");
        String updateFlag = outMap.get("updateFlag");

        PurApplyBill purApplyBill = new PurApplyBill();
        purApplyBill.setPurApplyId(purApplyTaskVo.getPurApplyId());
        purApplyBill.setUpdateBy(username);
        purApplyBill.setUpdateTime(newDate);
        purApplyBill.setApplyTime(newDate);
        purApplyBill.setApprovalTime(newDate);
        //需更新审批人信息
        if(updateFlag.equals("true")){
            purApplyBill.setApprovalUser(approvalUser);
            purApplyBill.setApprovalNode(taskName);
        }
        purApplyBill.setApprovalStatus(approvalStatus);
        purApplyBillMapper.updateByPrimaryKeySelective(purApplyBill);


        if(StringUtils.equals(approvalStatus,"审批结束") || StringUtils.equals(approvalStatus,"已终止")){
            PurMainBill purMainBill = new PurMainBill();
            purMainBill.setPurMainId(purApplyTaskVo.getPurMainId());
            purMainBill.setExecuteStatus(approvalStatus);
            purMainBill.setEndUser(username);
            purMainBill.setEndUserName(name);
            purMainBill.setEndTime(newDate);
            purMainBill.setUpdateBy(username);
            purMainBill.setUpdateTime(newDate);
            purMainBillMapper.updateByPrimaryKeySelective(purMainBill);

            PurNodeBill purNodeBill = new PurNodeBill();
            purNodeBill.setPurMainId(purApplyTaskVo.getPurMainId());
            purNodeBill.setExecuteNode("采购申请审批");
            purNodeBill.setExecuteStatus(approvalStatus);
            purNodeBill.setCreateBy(username);
            purNodeBill.setCreateTime(newDate);
            purNodeBillMapper.insertSelective(purNodeBill);
        }
    }


    /**
     * 分页查询当前用户的审批历史信息，记录信息
     * @param queryMap
     * @return
     */
    @Override
    public List<PurApplyTaskVo> queryApplyApprovalHisList(Map<String,String> queryMap){
        return purApplyBillMapperComp.selectApplyApprovalHisList(queryMap);
    }
}
